#include "graphicsmanager.h"

#include <gl/gl.h>

using namespace std;

bool GraphicsManager::FontLoaded = false;
Texture* GraphicsManager::Font = nullptr;

void GraphicsManager::DrawRectangle(float x, float y, float width, float height, Color color){
	float x1 = x;
	float y1 = y;
	float x2 = x1 + width;
	float y2 = y1 + height;
	glDisable(GL_TEXTURE_2D);
	glBegin(GL_QUADS);{
		color.SetColor();
		glVertex2d(x1, y1);
		glVertex2d(x1, y2);
		glVertex2d(x2, y2);
		glVertex2d(x2, y1);
	}glEnd();
}

void GraphicsManager::DrawString(double x, double y, string Text){
	InitFont();
	Color(1,1,1).SetColor();
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, Font->ID);
	for (int i = 0; i < (int)Text.size(); i++){
		DrawChar(x + (i*16), y, Text[i]);
	}
}

void GraphicsManager::DrawChar(double x, double y, char Char){
	double x1 = x;
	double y1 = y;
	double x2 = x + 16;
	double y2 = y + 16;

	double TexL = ((Char % 16) * 16) / (Font->Width * 1.0);
	double TexT = ((Char / 16) * 16) / (Font->Height * 1.0);
	double TexR = TexL + (16.0/Font->Width);
	double TexB = TexT + (16.0/Font->Height);

	glBegin(GL_QUADS);
		glTexCoord2d(TexL, TexT); glVertex2d(x1, y1);
		glTexCoord2d(TexR, TexT); glVertex2d(x2, y1);
		glTexCoord2d(TexR, TexB); glVertex2d(x2, y2);
		glTexCoord2d(TexL, TexB); glVertex2d(x1, y2);
	glEnd();
}

void GraphicsManager::InitFont(){
	if (!FontLoaded){
		Font = new Texture("font.png");
		FontLoaded = true;
	}
}
